<template>
    <el-row class="login-container" justify="center" :align="'middle'">
        <el-card style="max-width:480px;">
            <template #header>
                <div class="card-header">
                    <img :src="imgUrl" alt="">
                </div>
            </template>
            <div class="jump-link">
                <el-link type="primary" @click="handleChange">
                    {{ formType ? '返回登录' : '注册账号' }}
                </el-link>
            </div>
            <el-form ref="loginFormRef" :model="loginForm" style="max-width: 600px;" class="demo-ruleForm"
                :rules="rules">
                <el-form-item prop="userName">
                    <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="UserFilled" />
                </el-form-item>
                <el-form-item prop="passWord">
                    <el-input v-model="loginForm.passWord" type="password" placeholder="密码" :prefix-icon="Lock" />
                </el-form-item>
                <el-form-item v-if="formType" prop="validCode">
                    <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock">
                        <template #append>
                            <span class="countdown" @click="countdownChange">{{ countdown.validText }}</span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" style="width: 100%;" @click="submitForm(loginFormRef)">
                        {{ formType ? '注册' : '登录' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-row>
</template>

<script setup lang="ts">
import { ref, reactive, toRaw } from 'vue';
import { Lock, UserFilled } from '@element-plus/icons-vue';
import { getCode, UserAuthentication, Login, userMenuPermissions } from '../../api/index'
import type { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router';
import { CounterStore } from '../../store/index'

const router = useRouter();
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href;
// 切换表单
const formType = ref(false);
// 表单初始数据
const loginForm: {
    userName: string;
    passWord: string;
    validCode: string;
} = reactive({
    userName: "",
    passWord: "",
    validCode: ""
});

//账号校验规则
const validateUser = (rule: any, value: string, callback: (error?: Error) => void) => {
    // 检验账号不为空
    if (value === '') {
        callback(new Error('请输入账号'));
    } else {
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号'));
    }
}
// 密码校验规则
const validatePass = (rule: any, value: string, callback: (error?: Error) => void) => {
    // 检验密码不为空
    if (value === '') {
        callback(new Error('请输入密码'));
    } else {
        const reg = /^[a-zA-Z0-9_-]{4,16}$/;
        reg.test(value) ? callback() : callback(new Error('密码格式不对需要4到16位字符'));
    }
}
// 表单校验
const rules = reactive({
    userName: [{ validator: validateUser, trigger: 'blur' }],// 用户名
    passWord: [{ validator: validatePass, trigger: 'blur' }]//密码
})
// 点击切换登录/注册
const handleChange = () => {
    formType.value = !formType.value;
}
// 发送验证码时倒计时
const countdown: {
    validText: string;
    time: number;
} = reactive({
    validText: '获取验证码',
    time: 60
})
//记录当前定时器的状态
let flag = false;
// 发送验证码
const countdownChange = () => {
    // 如果发送就不处理
    if (flag) return;
    // 判断手机号是否正确
    // 手机号正则
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    // // 密码正则
    // /^[a-zA-Z0-9_-]{4,16}$/
    if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
        return ElMessage({
            message: '请检查手机号是否正确',
            type: 'warning',
        })
    }
    //定时器
    const time = setInterval(() => {
        if (countdown.time <= 0) {
            countdown.validText = '获取验证码';
            countdown.time = 60;
            clearInterval(time)
        } else {
            countdown.time -= 1;
            countdown.validText = `剩余${countdown.time}秒`
        }
    }, 1000)
    flag = true;
    getCode({ tel: loginForm.userName }).then(({ data }) => {
        if (data.code === 10000) {
            ElMessage.success('发送成功')
        }
    })
}

// 表单提交
const loginFormRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    // 手动触发表单校验
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 用户注册
            if (formType.value) {
                UserAuthentication(loginForm).then(({ data }) => {
                    if (data.code === 10000) {
                        ElMessage.success('注册成功，请登录');
                        formType.value = !formType.value;
                    }
                })
            } else {
                Login(loginForm).then(({ data }) => {
                    if (data.code === 10000) {
                        ElMessage.success('登录成功');
                        // 将token和用户信息缓存到浏览器
                        localStorage.setItem('pz_token', data.data.token);
                        // stringify将对象转为字符串
                        localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo));
                        userMenuPermissions().then(({ data }) => {
                            store.dynamicMenu(data.data);
                            // toRaw 可以将响应式数据转化为路由数据
                            toRaw(store.state.routerList).forEach((item: { path: string; redirect: string }) => {
                                router.addRoute('main', item)
                            })
                            // if(store.state.routerList[0].meta.children){
                            //     router.push(store.state.routerList[0].children[0].meta.path);
                            // }else{
                            //     router.push(store.state.routerList[0].meta.path);
                            // }      
                            router.push('/');     
                        })
                    } else {
                        ElMessage.error(data.message);
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 存储动态路由的方法
const store = CounterStore();

</script>

<style scoped lang="less">
:deep(.el-card__header) {
    padding: 0;
}

.login-container {
    height: 100%;

    .card-header {
        background-color: #899fe1;

        img {
            width: 430px;
        }
    }

    .jump-link {
        text-align: right;
        margin-bottom: 10px;
    }

    .countdown {
        cursor: pointer;
    }
}
</style>